<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package      Feather-CM
 * @subpackage   Auth
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 *  
 * @requires     SessionComponent
 */

class AuthComponent
{
	public $id         = 'Anonymous';
	public $identified = false;
	
	protected $groups  = array('anonymous');
	protected $Session;
	
	function startup(Controller $controller)
	{
		$this->controller = $controller;
		$this->Session    = $controller->Session;
		
		if ($this->Session->check('Member'))
		{
			// already logged-in
			$this->login($this->Session->read('Member'));
		}
		elseif (isset($_COOKIE['FeatherRemember']))
		{
			// auto-login
			list($uid, $pwd) = unserialize(base64_decode($_COOKIE['FeatherRemember']));
			$member = $controller->load->model('Member');
			$data   = $member->login($uid, $pwd);
			
			if (is_array($data))
				$this->login($data);
		}
	}
	
	// auth
	
	function login(&$member)
	{
		$this->__setMember(true, $member['id'], &$member['groups']);
		$this->Session->write('Member', &$member);
	}
	
	function remember($uid, $pwd, $set=true)
	{
		if ($set)
		{
			$data = base64_encode(serialize(array($uid, $pwd)));
			setcookie('FeatherRemember', $data, time() + 3600*24*30, '/'/*, '.'.env('HTTP_HOST')*/);
		}
		else {
			setcookie('FeatherRemember', null, time()-1, '/'/*, '.'.env('HTTP_HOST')*/);
		}
	}
	
	function logout()
	{
		$this->__setMember(false, 'Anonymous', array('anonymous'));
		$this->Session->delete('Member');
		setcookie('FeatherRemember', null, time()-1, '/'/*, '.'.env('HTTP_HOST')*/);
	}
	
	function permissionDenied()
	{
		if ($this->identified)
		{
			$url = empty($this->controller->params['url']['referer']) ? '/' :
				$this->controller->params['url']['referer'];
			$this->controller->flash(_('Permission denied'), $url, 403);
		}
		else {
			$this->controller->flash(_('Access is restricted, please sign in'), '/members/login');
		}
	}
	
	function inGroup($groups)
	{
		if (!is_array($groups))
			$groups = explode(',', str_replace(' ', '', $groups));
		$groups = array_intersect($this->groups, $groups);
		return !empty($groups);
	}
	
	// internals
	
	protected function __setMember($identified, $id, $groups)
	{
		$this->identified =  $identified;
		$this->id         =  $id;
		$this->groups     =& $groups;
	}
}
?>